package com.itheima.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 发送QQ邮箱验证码
 * @author 郭文亮
 * @since 2021/11/7 14:37
 */
public class SendEmail {
    private static Properties properties = null;
    private static Authenticator authenticator = null;
    static {
        // 创建Properties类用于记录邮箱的一些属性
        properties = new Properties();
        // 表示SMTP发送邮件，必须进行身份验证
        properties.put("mail.smtp.auth",true);
        // 此处填写SMTP服务器
        properties.put("mail.smtp.host","smtp.qq.com");
        // 端口号，QQ邮箱端口587
        properties.put("mail.smtp.port","587");
        // 此处填写，写信人的账号
        properties.put("mail.user","840984302@qq.com");
        // 此处填写16位SMPP口令
        properties.put("mail.password","xoiaiwsxgerfbcjg");

        // 构建授权信息，用于SMTP进行身份验证
        authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                String username = properties.getProperty("mail.user");
                String password = properties.getProperty("mail.password");
                return new PasswordAuthentication(username,password);
            }
        };
    }

    public static void sendMail(String toEmail,String code) throws MessagingException {
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(properties,authenticator);
        // 创建邮件信息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress from = new InternetAddress(properties.getProperty("mail.user"));
        message.setFrom(from);
        // 设置收件人的邮箱
        InternetAddress to = new InternetAddress(toEmail);
        message.setRecipient(Message.RecipientType.TO,to);
        // 设置邮件标题
        message.setSubject("用户注册验证");
        // 设置邮件的内容
        message.setContent("验证码："+code,"text/html;charset=UTF-8");
        // 发送邮件
        Transport.send(message);
    }
}
